package com.sdust.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/book/*"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        boolean isLogin = (session != null && session.getAttribute("username") != null);

        if (isLogin) {
            System.out.println("已登陆");
            chain.doFilter(request, response);
        } else {
            System.out.println("没有登陆");
            httpResponse.sendRedirect("/exp6/user/login.jsp");
        }

        // String loginURI = httpRequest.getContextPath() + "/login.jsp";
        //
        // boolean isLoginRequest = httpRequest.getRequestURI().equals(loginURI);
        //
        // if (isLoggedIn || isLoginRequest) {
        //     // 放行
        //     chain.doFilter(request, response);
        // } else {
        //     // 重定向到登录页面
        //     httpResponse.sendRedirect(loginURI);
        // }
    }
}
